// 模块插件列表
var gulp = require('gulp');

// CSS 预编译模块
var less = require('gulp-less'); // LESS

// 压缩css模块
var minifycss = require('gulp-minify-css');

// file system 模块
var fs = require('fs');

// 目录路径模块
var path = require('path');

// 重命名模块
var rename = require('gulp-rename'); 

// 监控文件模块
var watch  = require('gulp-watch'); 

// 删除文件模块
var clean = require('gulp-clean'); 

// 替换模块
var replace = require('gulp-replace'); 

// node 命令行传参模块
var minimist = require('minimist');

// 命令行颜色块
var color = require('colors');

// 文件合并模块
var concat = require('gulp-concat');

// 本地测试数据服务器
const spawn = require('child_process').spawn;

// Javascript压缩模块
var uglify = require('gulp-uglify');

// 静态资源文件MD5版本号
var rev = require('gulp-rev'); 

// 静态资源替换
var revCollector = require('gulp-rev-collector');

// Webpack & vue & es6
var webpackConfig = require('./webpack.config.js');
var webpack = require("webpack");

// CDN源
var CDN = "http://cdn.stosz.com";

// 是否开发模式
var develop_mode = true; 

// 存放编译任务输出的目录
var destination = ""; 

// 站目录结构
const Project = {
    build: {
        base: "./build/"
        , js: "./build/js/"
        , css: "./build/style/"
        , html: "./build/*.html"
    }
    , develop: {
        base: "./develop/"
        , html: "./develop/*.html"
        , css: "./develop/style/*.css"
        , js: "./develop/js/*.js"
    }
    , source: {
        base: "./source/"
        , html: "./source/template/*.html"
        , less: "./source/less/*.less"
        , plugins: "./source/plugins/**/*.*"
        , images: "./source/images/**/*.jpg"
    }
}

gulp.task("server", function(){
   spawn("node", ["static-server.js"]);
});

// 默认任务
gulp.task('default', function(){

});

// 开发任务
gulp.task('develop', function(){
    develop_mode = true;
    destination = !develop_mode ? Project.build.base : Project.develop.base;
    gulp.run(['html', 'less', 'images', 'plugins', 'webpack', 'replaceStaticFile', 'watch']);
});


// HTML
gulp.task('html', function(){
    return gulp.src( Project.source.html )
        .pipe(gulp.dest(destination));
});

// 编译 LESS
gulp.task('less', function () {
    return gulp.src( Project.source.less )
        .pipe(less())
        .pipe(replace('{{ resouce-origin }}', !develop_mode ? "/build" : "/develop"))
        .pipe(gulp.dest( destination + "style/" ));
});

// 复制 images
gulp.task('images', function(){
    return gulp.src( Project.source.images )
        .pipe(gulp.dest( destination + 'images/' ));
});

// 复制 plugins
gulp.task('plugins', function(){
    return gulp.src( Project.source.plugins )
        .pipe(gulp.dest( destination + 'plugins' ));
});

// 打包vue
gulp.task("webpack", function(callback) {
    var myConfig = Object.create(webpackConfig);
        webpack(myConfig, function(err, stats) {
        callback();
    });
});
gulp.task('watch',function(){
    gulp.watch([ Project.source.html ], ['html']);
    gulp.watch(['./source/vue/main.js'], ['webpack']);
    gulp.watch(['./source/vue/login.js'], ['webpack']);
    gulp.watch(['./source/vue/**/*.vue'], ['webpack']);
    gulp.watch(['./source/less/**/*.less'], ['less', 'replaceStaticFile']);
});


// 替换静态资源
gulp.task('replaceStaticFile', ['html', 'less', 'webpack'], function(){
    gulp.src( Project.develop.html )
        .pipe(replace('{{ resouce-origin }}', "/develop"))
        .pipe(gulp.dest( destination ));
    gulp.src(['./index.php'])
        .pipe(replace("require_once 'build/", "require_once 'develop/"))
        .pipe(gulp.dest( './' ));
});

// =====================================================================

// 生成 build
gulp.task('build', function(){
    develop_mode = false;
    destination = !develop_mode ? Project.build.base : Project.develop.base;
    gulp.run(['html', 'less', 'images', 'plugins', 'version']);
});

// 推送到七牛CDN
gulp.task('build2', ['qniuPush'], function(){});


// JS - 压缩并生成版本号
gulp.task('version', ['html', 'less'], function(){
    gulp.src( Project.develop.js )
        .pipe(uglify())
        .pipe(rev())
        .pipe(gulp.dest( Project.build.js ))
        .pipe(rev.manifest())
        .pipe(gulp.dest( Project.build.js ));
    gulp.src( "./build/style/*.css" )
        .pipe(minifycss())
        .pipe(rev())
        .pipe(gulp.dest( Project.build.css ))
        .pipe(rev.manifest())
        .pipe(gulp.dest( Project.build.css ));
});

gulp.task('qniuPush', function(){
    develop_mode = false;
    destination = !develop_mode ? Project.build.base : Project.develop.base;
    gulp.src(['./build/js/*.json', './build/style/*.json', Project.build.html])
        .pipe(revCollector())
        .pipe(replace('{{ resouce-origin }}', CDN + "/build"))
        .pipe(gulp.dest( destination ));
    gulp.src(['./index.php'])
        .pipe(replace("require_once 'develop/", "require_once 'build/"))
        .pipe(gulp.dest( './' ));

    var filelist = fs.readdirSync('./build/js/');
    var filelistName = [];
        filelist.map(function(filename){
            if( filename.indexOf('.json') < 0 ){
                filelistName.push(filename);
            }
        });
        filelistName.map(function(filename){
            var key = "build/js/"+filename;
            var token = uptoken(qiniu.conf.bucket, key);
            uploadFile(token, key, './build/js/' + filename);
        });

    var filelist = fs.readdirSync('./build/style/');
    var filelistName = [];
        filelist.map(function(filename){
            if( filename.indexOf('.json') < 0 ){
                filelistName.push(filename);
            }
        });
        filelistName.map(function(filename){
            var key = "build/style/"+filename;
            var token = uptoken(qiniu.conf.bucket, key);
            uploadFile(token, key, './build/style/' + filename);
        });
});

var qiniu = require("qiniu");
    qiniu.conf.ACCESS_KEY = '78fG28aSTgzk7JX-Pv0xV_m10teJEHGLv9BA87Q2';
    qiniu.conf.SECRET_KEY = '98xNYHdAvkrWxNd3wYkzjw9qr9A9Wgif1h-wWhew';
    qiniu.conf.bucket = 'stoshop';

//构建上传策略函数
function uptoken(bucket, key) {
    var putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
    return putPolicy.token();
}

//构造上传函数
function uploadFile(uptoken, key, localFile) {
  var extra = new qiniu.io.PutExtra();
    qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
      if(!err) {
        console.log('upload succuess!')
      } else {
        console.log(err);
      }
  });
}



